package com.ai.bitcoin.aop;


import com.ai.bitcoin.annotation.Privilege;
import com.ai.bitcoin.annotation.PrivilegeEnum;
import com.ai.bitcoin.constant.JwtConstant;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.helper.JwtParseTokenHelper;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.util.JacksonUtils;
import com.ai.bitcoin.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


@Component(value = "apiPrivilegeAspect")
@Aspect
@Order(1)
public class PrivilegeAspect {
	
	private static final Logger logger = LoggerFactory.getLogger(PrivilegeAspect.class);
	
	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private JwtParseTokenHelper jwtParseTokenHelper;

	
	@Around(value="@annotation(com.ai.bitcoin.annotation.Privilege)")
	public Object doPrivilegeCheck(ProceedingJoinPoint pjp) throws Throwable {
		Object[] param = pjp.getArgs();
		HttpServletRequest request = (HttpServletRequest) param[0];
		Signature signature = pjp.getSignature();
		MethodSignature methodSignature = (MethodSignature)signature;
//		//这段代码获取的targetMethod对象是接口上的方法，他上面也是没有注解的
		Method targetMethod = methodSignature.getMethod();
//		//获得真实的方法
		Method realMethod = pjp.getTarget().getClass().getDeclaredMethod(signature.getName(), targetMethod.getParameterTypes());
		Privilege action = realMethod.getAnnotation(Privilege.class);
		PrivilegeEnum privilege = action.privilege();
		String token = request.getHeader("token");
		//校验权限
		if(privilege.equals(PrivilegeEnum.LOGIN)) {
			if(token == null) {
				logger.error("unlegal request,token is empty");
				return JacksonUtils.toJson(new GeneralReponse(JwtConstant.RESCODE_NOLOGIN, "unlegal request"));
			}
			BccUser user = jwtParseTokenHelper.parseToken(token);
			request.setAttribute("user", user);
		} else {
			if(token != null) {
				BccUser user = jwtParseTokenHelper.parseToken(token);
				request.setAttribute("user", user);
			}
		}
		return pjp.proceed();
	}



}
